package dao;


import pojo.Books;
import pojo.BorrowRecords;
import pojo.Users;
import pojo.ViolationRecords;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.List;

public class BooksDao extends BaseDao{
    /**
     * 添加书籍并返回添加行数（添加书籍数目）
     * @param books
     * @return
     */
    public int addBook(Books books){
        System.out.println("这里是addBook的Dao层");
        String sql = "insert into books(book_id,title,author,available) value (DEFAULT,?,?,DEFAULT)";
        int rows = baseUpdate(sql,books.getTitle(),books.getAuthor());
        return rows;
    }

    /**
     * 查找书籍目录放到list集合中遍历展示
     * @return
     */
    public List<Books> findAllBook(){
        System.out.println("这里是findAllBook的Dao层");
        String sql = "select book_id bookId,title,author,available from books";
        List<Books> list = baseQuery(Books.class,sql);
//        迭代遍历
        list.forEach(System.out::println);
        return list;
    }

    /**
     *完成借书的信息修改功能
     * @param bookId
     * @param userId
     * @return
     */
    public int borrowBook(int bookId,Integer userId){
        System.out.println("这里是borrowBook的Dao层");
//        将available改为0
        String sql1 = "update books set available = 0 where book_id=?";
        int row1 = baseUpdate(sql1,bookId);
//        在borrow_records添加借书信息
        String sql2 = "INSERT INTO borrow_records(record_id,user_id, book_id, borrow_date, due_date) VALUES (DEFAULT,?,?, NOW(), NOW() + INTERVAL 7 DAY)";
        int row2 = baseUpdate(sql2,userId,bookId);

        return (row1>0 && row2>0)?1:0;
    }

    /**
     *根据user_id查找用户借的书
     * @param userId
     * @return
     */
    public List<Books> findBookByUserId(Integer userId) {
        System.out.println("这里是findBookByUserId的Dao层");
        String sql = "select book_id bookId,title,author,available from books where book_id=(select book_id bookId from borrow_records borrowRecords where user_id = ?)";
        List<Books> booksList = baseQuery(Books.class,sql,userId);
        System.out.println(booksList.toString());
        return booksList;
    }

    /**
     *实现还书功能
     * @param bookId
     * @param userId
     * @return
     */
    public int returnBook(int bookId,Integer userId) {
        System.out.println("这里是borrowBook的Dao层");
        //        将available改为1
        String sql1 = "update books set available = 1 where book_id=?";
        int row1 = baseUpdate(sql1,bookId);
//        更新实际归还时间return_date,
        String sql3 = "update borrow_records set return_date = now() where book_id=?";
        int row3 = baseUpdate(sql3,bookId);
//        获取return_date 和 borrow_date
        String sqlr="select return_date returnDate from borrow_records where book_id=?";
        String sqlb="select borrow_date borrowDate from borrow_records where book_id=?";
        LocalDateTime ret = baseQueryObject(LocalDateTime.class,sqlr,bookId);
        LocalDateTime bor = baseQueryObject(LocalDateTime.class,sqlb,bookId);
        System.out.println("还书时间= "+ret);
        System.out.println("借书时间= "+bor);
        // 计算两个时间点之间的差异
//        Duration duration = Duration.between(ret, bor);
//
//        LocalDateTime date = ret.getReturnDate()-bor.getReturnDate();
        Period period = Period.between(bor.toLocalDate(), ret.toLocalDate());
        System.out.println("借书还书相隔时间= "+period);

//        检查是否超时（return_date - borrow_date >7），
//        是则violation_count+1并记录超时时长overdue_days;否则无操作
        // 计算两个时间点之间的持续时间
        Duration duration = Duration.between(bor, ret);

        // 获取持续时间的天数、小时数、分钟数和秒数
        long daysBetween = duration.toDays(); // 计算完整天数

        // 打印结果
        System.out.println("天数: " + daysBetween);

        if(daysBetween > 7){
            System.out.println("日期差异超过7天，记1次违规");
//            添加违规记录
            String sqlAdd = "update users set violation_count=violation_count+1 where user_id=?";
            int row4 = baseUpdate(sqlAdd,userId);
//            查找用户违规次数
            String sqlNum = "select violation_count violationCount from users where user_id=?";
            int row5 = baseQueryObject(int.class,sqlNum,userId);
//            判断违规次数是否>=3，是则禁用用户
            if(row5 >= 3){
                System.out.println("违规次数>=3,禁用用户");
            }
            String sqlNock = "update users set status=0 where user_id=?";
            int row6 = baseUpdate(sqlNock,userId);
        }else {
            System.out.println("日期差异不超过7天");
        }

        //        在borrow_records删除借书信息
        String sql2 = "delete from borrow_records where book_id=?";
        int row2 = baseUpdate(sql2,bookId);

        return (row1>0 && row2>0)?1:0;
    }

    /**
     *根据user_id查找借书信息
     * @param userId
     * @return
     */
    public List<BorrowRecords> findBorrowRecordsByUserId(Integer userId) {
        System.out.println("这里是findBorrowRecordsByUserId的Dao层");
        String sql = "select borrow_date borrowDate,due_date dueDate from borrow_records where user_id= ?";
        List<BorrowRecords> borrowRecordsList = baseQuery(BorrowRecords.class,sql,userId);
        System.out.println(borrowRecordsList.toString());
        return borrowRecordsList;
    }
}
